from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Q
from .models import Order
from products.models import Product
from django.db import transaction

@login_required
def order_list(request):
    """订单列表视图"""
    query = request.GET.get('q', '')
    orders = Order.objects.filter(user=request.user)
    
    if query:
        orders = orders.filter(
            Q(product__name__icontains=query) |  # 搜索商品名称
            Q(address__icontains=query) |  # 搜索收货地址
            Q(phone__icontains=query) |  # 搜索联系电话
            Q(status__icontains=query)  # 搜索订单状态
        )
    
    # 按创建时间倒序排序
    orders = orders.order_by('-created_at')
    
    return render(request, 'orders/order_list.html', {
        'orders': orders,
        'query': query
    })

@login_required
def create_order(request, product_id):
    """创建订单视图"""
    product = get_object_or_404(Product, pk=product_id)
    
    if request.method == 'POST':
        try:
            # 获取并验证数量
            quantity = int(request.POST.get('quantity', 1))
            if quantity <= 0:
                messages.error(request, '购买数量必须大于0')
                return redirect('products:product_detail', pk=product_id)
            
            if quantity > product.stock:
                messages.error(request, '商品库存不足')
                return redirect('products:product_detail', pk=product_id)
            
            # 获取并验证地址和电话
            address = request.POST.get('address', '').strip()
            phone = request.POST.get('phone', '').strip()
            
            if not address:
                messages.error(request, '请填写收货地址')
                return redirect('products:product_detail', pk=product_id)
                
            if not phone:
                messages.error(request, '请填写联系电话')
                return redirect('products:product_detail', pk=product_id)
            
            with transaction.atomic():
                # 创建订单
                order = Order.objects.create(
                    user=request.user,
                    product=product,
                    quantity=quantity,
                    total_price=product.price * quantity,
                    address=address,
                    phone=phone
                )
                # 更新库存
                product.stock -= quantity
                product.save()
                
                messages.success(request, '订单创建成功！')
                return redirect('orders:order_list')
                
        except ValueError:
            messages.error(request, '请输入有效的购买数量')
        except Exception as e:
            messages.error(request, f'创建订单失败：{str(e)}')
        return redirect('products:product_detail', pk=product_id)
    
    return render(request, 'orders/create_order.html', {'product': product})

@login_required
def update_order(request, pk):
    """更新订单视图"""
    order = get_object_or_404(Order, pk=pk, user=request.user)
    
    if request.method == 'POST':
        status = request.POST.get('status')
        if status and status in dict(Order.STATUS_CHOICES):
            order.status = status
            order.save()
            messages.success(request, '订单状态更新成功！')
            return redirect('orders:order_list')
    
    return render(request, 'orders/update_order.html', {'order': order})

@login_required
def delete_order(request, pk):
    """删除订单视图"""
    order = get_object_or_404(Order, pk=pk, user=request.user)
    if order.status == 'pending':
        # 恢复库存
        order.product.stock += order.quantity
        order.product.save()
        order.delete()
        messages.success(request, '订单已成功取消！')
    else:
        messages.error(request, '只能取消待支付的订单！')
    return redirect('orders:order_list')
